<template>
  <div class="app-container">
    <!-- <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="奖品" prop="prize">
        <el-input
          v-model="queryParams.prize"
          placeholder="请输入奖品"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="积分" prop="requiredPoints">
        <el-input
          v-model="queryParams.requiredPoints"
          placeholder="请输入积分"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="概率" prop="probability">
        <el-input
          v-model="queryParams.probability"
          placeholder="请输入概率"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="数量" prop="number">
        <el-input
          v-model="queryParams.number"
          placeholder="请输入数量"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="抽奖模式" prop="lotteryMode">
        <el-select v-model="queryParams.lotteryMode" placeholder="请选择抽奖模式" clearable size="small">
          <el-option
            v-for="dict in lotteryModeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form> -->
    <div class="titleBox">
      <div class="titleBoxIn">当前抽奖模式:{{prizeModel == 1?'大转盘':'答题'}}</div>
      <el-button type="primary" size="small" @click="setCountShow = true">设置{{prizeModel == 1?'抽奖':'答题'}}次数</el-button>
      <el-button type="primary" size="small" @click="modelShow = true" class="lottoBtn">编辑抽奖模式</el-button>
      <el-button type="primary" size="small" @click="lottoShow = true" class="lottoBtn">编辑转盘中奖概率</el-button>
    </div>
    <el-dialog :close-on-click-modal="false" v-loading.fullscreen="loading" title="大转盘中奖概率设置" :visible.sync="lottoShow" width="500px" append-to-body>
      <div class="tips">所填概率之和必须为100</div>
      <el-form label-width="100px">
        <el-form-item v-for="(item,index) in lottoPrizeList" :key="index" :label="item.prize" prop="prize">
          <el-input v-model="item.probability" placeholder="请输入概率（单位：%）"  @input="item.probability = item.probability.replace(/[^\.\d]/g,'')"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="changePrize">确 定</el-button>
        <el-button @click="cancelChangePrize">取 消</el-button>
      </div>
    </el-dialog>
    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['prize:prize:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['prize:prize:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['prize:prize:remove']"
        >删除</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['prize:prize:export']"
        >导出</el-button>
      </el-col> -->
      <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
    </el-row>

    <!-- <el-table v-loading="loading" :data="prizeList" @selection-change="handleSelectionChange"> -->
    <el-table v-loading="loading" :data="prizeList">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <!-- <el-table-column label="id" align="center" prop="id" /> -->
      <el-table-column label="序号" type="index" :index="(queryParams.pageNum-1)*10+1" />
      <el-table-column label="活动名称" align="center" prop="nameEvent" />
      <el-table-column label="奖品" align="center" prop="prize" />
      <el-table-column label="积分" align="center" prop="requiredPoints" />
      <el-table-column label="概率" align="center" prop="probability" />
      <el-table-column label="数量" align="center" prop="number" />
      <el-table-column label="剩余数量" align="center" prop="leftNumber" />
      <el-table-column label="抽奖模式" align="center" prop="lotteryMode" :formatter="lotteryModeFormat" />
      <el-table-column label="创建时间" align="center" prop="createTime" />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['prize:prize:edit']"
          >修改</el-button>
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['prize:prize:remove']"
          >删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    
    <!-- <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    /> -->

    <!-- 添加或修改奖品对话框 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="活动名称" prop="nameEvent" v-if="this.form.lotteryMode == 1">
          <el-input v-model="form.nameEvent" placeholder="请输入活动名称"/>
        </el-form-item>
        <el-form-item label="奖品" prop="prize">
          <el-input v-model="form.prize" placeholder="请输入奖品" />
        </el-form-item>
        <el-form-item label="奖品图片" :class="form.prizeImages?'upHide':''" prop="prizeImages" v-if="this.form.lotteryMode == 0">
          <!-- <el-input v-model="form.prize" placeholder="请输入奖品" /> -->
          <el-upload
            ref="upload"
            :action="$uploadImage"
            list-type="picture-card"
            :on-success="uploadSuccess"
            :on-remove="removeImage"
            :file-list="imageList"
            :headers="headers"
            name="fileList"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="奖品类型" prop="integralMode" v-if="form.lotteryMode!=1">
          <el-radio v-model="form.integralMode" :label="0">积分</el-radio>
          <el-radio v-model="form.integralMode" :label="1">实物</el-radio>
        </el-form-item>
        <el-form-item label="积分" prop="requiredPoints" v-if="this.form.integralMode != 1||form.lotteryMode==1">
          <el-input v-model="form.requiredPoints" placeholder="请输入积分" @input="form.requiredPoints = form.requiredPoints.replace(/[^\.\d]/g,'')"/>
        </el-form-item>
        <!-- <el-form-item label="概率" prop="probability">
          <el-input v-model="form.probability" @input="gailvChange" placeholder="请输入概率" />
        </el-form-item> -->
        <el-form-item label="数量" prop="number">
          <el-input v-model="form.number" placeholder="请输入数量"  @input="form.number = form.number.replace(/[^\.\d]/g,'')"/>
        </el-form-item>
        <!-- <el-form-item label="抽奖模式" prop="lotteryMode">
          <el-select v-model="form.lotteryMode" placeholder="请选择抽奖模式">
            <el-option
              v-for="dict in lotteryModeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" title="抽奖模式选择" :visible.sync="modelShow" width="500px" append-to-body>
      <el-radio v-model="prizeModel" :label="1" size="large">大转盘</el-radio>
      <el-radio v-model="prizeModel" :label="2" size="large">答题</el-radio>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="chooseModel">确 定</el-button>
        <el-button @click="modelShow = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" :title="'设置每日'+(prizeModel == 1?'抽奖':'答题')+'次数'" :visible.sync="setCountShow" width="500px" append-to-body>
      <el-input :placeholder="'请输入'+(prizeModel == 1?'抽奖':'答题')+'次数'" v-model="prizeCount" @input="prizeCount = prizeCount.replace(/[^\.\d]/g,'')"></el-input>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="setCount">确 定</el-button>
        <el-button @click="setCountShow = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { setPrizeCount,getPrizeCount,getExamCount,updateAllPrize,getModel,chooseModel,listPrize, getPrize, delPrize, addPrize, updatePrize, exportPrize } from "@/api/prize/prize";
import { getToken } from '@/utils/auth'

export default {
  name: "Prize",
  components: {
  },
  data() {
    return {
      prizeCount:'', // 抽奖次数
      setCountShow:false, // 设置抽奖次数显示
      lottoShow:false,
      lottoPrizeList:[],
      imageList:[],
      prizeModel:1,
      modelShow:false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 奖品表格数据
      prizeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 抽奖模式字典
      lotteryModeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        prize: null,
        requiredPoints: null,
        probability: null,
        number: null,
        lotteryMode: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        prize:[
          {required:true,message:'请填写奖品',trigger: 'change'}
        ],
        prizeImages:[
          {required:true,message:'请选择奖品图片',trigger: 'change'}
        ],
        requiredPoints:[
          {required:true,message:'请填写积分',trigger: 'change'}
        ],
        // probability:[
        //   {required:true,message:'请填写概率0-100',trigger: 'change'}
        // ],
        number:[
          {required:true,message:'请填写数量',trigger: 'change'}
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getModel();
    this.getDicts("sys_lottery_mode").then(response => {
      this.lotteryModeOptions = response.data;
    });
  },
  computed:{
    headers(){
      return {
        'Authorization':'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
      }
    }
  },
  methods: {
    // 获取抽奖次数
    getCount(){
      if(this.prizeModel == 1){
        getPrizeCount()
        .then(res=>{
          console.log(res,'抽奖次数')
          this.prizeCount = res.data.dictValue
        })
      } else {
        getExamCount()
        .then(res=>{
          console.log(res,'答题次数')
          this.prizeCount = res.data.dictValue
        })
      }
    },
    // 设置抽奖次数
    setCount(){
      setPrizeCount({
        dictCode:this.prizeModel == 1?112:113,
        dictValue:this.prizeCount,
        dictType: "sys_lottery_number",
        dictLabel: this.prizeModel == 1?"大转盘抽奖次数":"答题次数"
      })
      .then(res=>{
        console.log(res,'设置次数')
        this.msgSuccess("设置成功");
        this.setCountShow = false
      })
      .catch(()=>{
        this.$message.warning("设置失败");
      })
    },
    cancelChangePrize(){
      this.lottoShow = false
      this.lottoPrizeList = JSON.parse(JSON.stringify(this.prizeList.filter(item=>item.lotteryMode==0)))
    },
    // 修改概率
    changePrize(){
      let flag = false
      let total = 0
      let arr = this.lottoPrizeList.map(item=>{
        if(item.probability === ""||item.probability === null){
          flag = true
        }
        total+=item.probability/1
        return item
      })
      arr.map(item=>{
        if(item.requiredPoints == '--'){
          console.log(111)
          item.requiredPoints = 0
        }
      })
      if(flag){
        this.$message.warning('请填写概率')
        return
      }
      console.log(total)
      if(total!=100){
        this.$message.warning('中奖概率之和必须为100')
        return
      }
      this.loading = true;
      updateAllPrize(arr)
      .then(res=>{
        this.loading = false;
        this.lottoShow = false
        this.msgSuccess("修改成功");
        this.getList();
      })
      .catch(()=>{
        this.loading = false;
      })
    },
    // 删除图片
    removeImage(){
      this.form.prizeImages = ""
      this.$refs.form.validateField(['prizeImages'])
    },
    // 上传成功
    uploadSuccess(e){
      console.log(e,'上传成功')
      this.$set(this.form,'prizeImages',e.data[0])
      this.form.prizeImages = e.data[0]
      this.form = JSON.parse(JSON.stringify(this.form))
      this.$nextTick(()=>{
        this.$refs.form.validateField(['prizeImages'])
      })
    },
    chooseModel(){
      chooseModel(this.prizeModel).then(()=>{
        this.msgSuccess("修改成功");
        this.modelShow = false
        this.getCount()
      }).catch(()=>{
        this.$message.warning("修改失败");
        this.getModel()
      })
    },
    getModel(){
      getModel().then((res)=>{
        console.log(res,'获取抽奖模式')
        this.prizeModel = res.data.data.prizeSwitch
        this.getCount()
      })
    },
    gailvChange(){
      this.form.probability = this.form.probability.replace(/[^\.\d]/g,'')
      if(this.form.probability){
        if(this.form.probability/1>100){
          this.form.probability = 100
        }
      }
    },
    /** 查询奖品列表 */
    getList() {
      this.loading = true;
      listPrize(this.queryParams).then(response => {
        this.prizeList = response.rows.map(item=>{
          if(item.lotteryMode == 1){
            item.probability = '--'
          } else {
            if(item.integralMode == 1){
              item.requiredPoints = '--'
            }
          }
          return item
        });
        this.lottoPrizeList = JSON.parse(JSON.stringify(response.rows.filter(item=>item.lotteryMode==0)))
        this.total = response.total;
        this.loading = false;
      });
    },
    // 抽奖模式字典翻译
    lotteryModeFormat(row, column) {
      return this.selectDictLabel(this.lotteryModeOptions, row.lotteryMode);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        isDelete: null,
        prize: null,
        integralMode:0,
        requiredPoints: null,
        probability: null,
        nameEvent:null,
        number: null,
        lotteryMode: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加奖品";
      this.imageList = []
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getPrize(id).then(response => {
        this.form = response.data;
        this.imageList = [{
          name:'图片',
          url:response.data.prizeImages
        }]
        if(this.form.lotteryMode == 0){
          this.rules = {
            prize:[
              {required:true,message:'请填写奖品',trigger: 'change'}
            ],
            prizeImages:[
              {required:true,message:'请选择奖品图片',trigger: 'change'}
            ],
            // requiredPoints:[
            //   {required:true,message:'请填写积分',trigger: 'change'}
            // ],
            probability:[
              {required:true,message:'请填写概率0-100',trigger: 'change'}
            ],
            number:[
              {required:true,message:'请填写数量',trigger: 'change'}
            ],
          }
        } else {
          this.rules={
            nameEvent:[
              {required:true,message:'请填活动名称',trigger: 'change'}
            ],
            prize:[
              {required:true,message:'请填写奖品',trigger: 'change'}
            ],
            requiredPoints:[
              {required:true,message:'请填写积分',trigger: 'change'}
            ],
            // probability:[
            //   {required:true,message:'请填写概率0-100',trigger: 'change'}
            // ],
            number:[
              {required:true,message:'请填写数量',trigger: 'change'}
            ],
          }
        }
        this.open = true;
        this.title = "修改奖品";
        this.$forceUpdate()
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.form.integralMode == 1&&this.form.lotteryMode!=1){
            this.form.requiredPoints = 0
          }
          if (this.form.id != null) {
            updatePrize(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPrize(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除奖品编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delPrize(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有奖品数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportPrize(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    }
  }
};
</script>
<style>
.upHide .el-upload{
  display: none;
}
</style>
<style scoped>
.titleBox{
  display: flex;
  align-items: center;
  justify-content: flex-start;
  margin-bottom: 20px;
}
.titleBoxIn{
  margin-right: 20px;
}
.lottoBtn{
  margin-left: 20px;
}
.tips{
  margin-bottom: 20px;
}
</style>